package com.tledu.springbootmybatis.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tledu.springbootmybatis.core.AjaxResult;
import com.tledu.springbootmybatis.domain.User;
import com.tledu.springbootmybatis.service.IUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author cyrus
 */
@Controller
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {

    private final IUserService userService;

    @RequestMapping()
    public String list(User user, Model model) {
        model.addAttribute("list", userService.list(user));
        return "user/list";
    }

    @PostMapping("list")
    @ResponseBody
    public AjaxResult<PageInfo<User>> listAjaxResult(User user, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<User> list = userService.list(user);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return new AjaxResult<PageInfo<User>>(pageInfo);
    }

    @GetMapping("/add")
    public String add() {
        return "user/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult<String> add(User user) {
        userService.insert(user);
        return new AjaxResult<String>("新增成功");
    }


    @GetMapping("/edit")
    public String edit(Integer id,Model model) {
        model.addAttribute("user", userService.selectById(id));
        return "user/edit";
    }

    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult<String> edit(User user) {
        userService.update(user);
        return new AjaxResult<String>("修改成功");
    }


    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public AjaxResult<String> delete(@PathVariable Integer id) {
        userService.delete(id);
        return new AjaxResult<String>("删除成功");
    }

}
